package com.hskn.hss.module.menu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.entity.MenuTreeEntity;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.button.entity.SysButton;
import com.hskn.hss.module.button.service.ISysButtonService;
import com.hskn.hss.module.menu.entity.SysMenu;
import com.hskn.hss.module.menu.mapper.SysMenuMapper;
import com.hskn.hss.module.menu.service.ISysMenuService;
import com.hskn.hss.utils.GeometryUtil;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.MenuTreeUtil;
import com.hskn.hss.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-04
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    @Resource
    SysMenuMapper sysMenuMapper;
    @Resource
    ISysButtonService sysButtonService;

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public AjaxResult insert(JSONObject params) throws HssException {
        SysMenu sysMenu = params.getObject("data", SysMenu.class);
        sysMenu.setId(StringUtils.uuid());
        if(StringUtils.isNotEmpty(sysMenu.getParentid())){
            SysMenu parentSysMenu = getById(sysMenu.getParentid());
            if(Objects.nonNull(parentSysMenu)){
                sysMenu.setParentName(parentSysMenu.getParentName());
            }
        }
        int i = sysMenuMapper.insert(sysMenu);
        List<SysButton> sysButtonList1 = new ArrayList<>();
        List<SysMenu> sysMenuList = new ArrayList<>();
        sysMenuList.add(sysMenu);
        if (CollectionUtils.isNotEmpty(sysMenuList)) {
            List<String> parenIds = sysMenuList.stream().map(SysMenu::getParentid).collect(Collectors.toList());
            sysMenuList = sysMenuList.stream().filter(s ->!parenIds.contains(s.getId())&&!s.getParentid().equals("0")).collect(Collectors.toList());
            sysMenuList.forEach(s -> {
                sysButtonList1.add(SysButton.builtSysButton(s,"添加","add","add"));
                sysButtonList1.add(SysButton.builtSysButton(s,"修改","edit","edit"));
                sysButtonList1.add(SysButton.builtSysButton(s,"查询","query","query"));
                sysButtonList1.add(SysButton.builtSysButton(s,"删除","delete","delete"));
                sysButtonList1.add(SysButton.builtSysButton(s,"导入","import","import"));
                sysButtonList1.add(SysButton.builtSysButton(s,"导出","export","export"));
            });
        }
        if (CollectionUtils.isNotEmpty(sysButtonList1)) {
            sysButtonService.saveBatch(sysButtonList1);
        }
        boolean flag = i > 0 ? true : false;

        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    public AjaxResult deleteByid(JSONObject params) throws HssException {
        String id = params.getString("id");
        SysMenu sysMenu = sysMenuMapper.selectById(id);
        if (StringUtils.isEmpty(sysMenu)) {
            return AjaxResult.fail("不存在的菜单");
        }
        sysMenuMapper.deleteById(id);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult update(JSONObject params) throws HssException {
        SysMenu sysMenu = params.getObject("data", SysMenu.class);

        int i = sysMenuMapper.updateById(sysMenu);
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    public SysMenu getInfoById(JSONObject params) throws HssException {
        String id = params.getString("id");
        SysMenu sysMenu = sysMenuMapper.selectById(id);
        return sysMenu;
    }

    @Override
    public List<SysMenu> getListByMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        map = params.getObject("queryparams", Map.class);
        List<SysMenu> MenusList = sysMenuMapper.selectByMap(map);
        return MenusList;
    }


    @Override
    public JSONObject getList(JSONObject params) throws HssException {
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();

        Map<String, Object> map = new HashMap();
        map.put("parentid", params.getString("parentid"));
        map.put("name", params.getString("name"));
        map.put("type", params.getString("type"));
        map.put("status", params.getString("status"));


        Page<SysMenu> menuPage = new Page<>(page, size, true);
        IPage<SysMenu> iPage = sysMenuMapper.listMenu(menuPage, map);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("menulist", iPage.getRecords());
        return json;
    }

    @Override
    public List<SysMenu> getMenuListByUserid(String uid) throws HssException {
        Map map = new HashMap();
        map.put("userid", uid);
        List<SysMenu> menuList = sysMenuMapper.getMenuListByUserid(uid);
        for (SysMenu sysmenu : menuList) {
            List<SysButton> buttonList = sysButtonService.GetButtonListByMenuId(sysmenu.getId());
            sysmenu.setSysbutton(buttonList);
        }
        return menuList;
    }

    @Override
    public List<MenuTreeEntity> getTreeList() {
        List<MenuTreeEntity> treeList = sysMenuMapper.getTreeList();
        Map<String,List<MenuTreeEntity>> menuTreeEntityMap = GroupingByUtils.getGroupingForMapList(treeList,MenuTreeEntity::getParentid);
        Map<String,List<SysButton>> buttonMap = sysButtonService.getListMap(new QueryWrapper<SysButton>().lambda().eq(SysButton::getStatus,
                "0")
        ,SysButton::getMenuid);
        return MenuTreeUtil.buildTreeList(treeList,menuTreeEntityMap,buttonMap);
    }
    @Override
    public List<SysMenu> selectList(Wrapper<SysMenu> queryWrapper) {
       return sysMenuMapper.selectList(queryWrapper);
    }
    @Override
    public Map<String,SysMenu> getSysMenuMap(Wrapper<SysMenu> queryWrapper) {
        List<SysMenu> sysMenuList = selectList(queryWrapper);
        Map<String,SysMenu> sysMenuMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(sysMenuList)){
            sysMenuMap = GroupingByUtils.getGroupingForMapEntity(sysMenuList,SysMenu::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        return sysMenuMap;
    }


}
